package wxshop.web.admin.tools;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * Created by 121874694@qq.com on 2018/3/4.
 */
public class XmlAndBean {
	public static <T> T toJavaBean(String xml,Class<T> tClass) throws JAXBException {
		T t = null;
		JAXBContext context = JAXBContext.newInstance(tClass);
		Unmarshaller unmarshal = context.createUnmarshaller();
		t = (T) unmarshal.unmarshal(new StringReader(xml));
		return  t;
	}
	public static String toXml(Object obj, String encoding) {
		String result = null;
		try {
			JAXBContext context = JAXBContext.newInstance(obj.getClass());
			Marshaller marshaller = context.createMarshaller();
			marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
			
			StringWriter writer = new StringWriter();
			marshaller.marshal(obj, writer);
			result = writer.toString();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
